<!--
 * @Descripttion:
 * @version: 1.0.0
 * @Author: htang
 * @Date: 2024-01-24 14:39:31
 * @LastEditors: htang
 * @LastEditTime: 2024-03-12 10:28:46
-->
<template>
  <div class="jeecg-basic-table station-list-view pump-room-container">
    <div class="tip">
      <span>水厂视频监控回放</span>
      <span class="tip-img"></span>
    </div>
    <div class="jeecg-search-layer">
      <a-form ref="form" :model="queryParam">
        <a-row :gutter="[16, 16]">
          <a-col :span="8">
            <a-form-item label="时间">
              <a-range-picker
                v-model:value="queryParam.dateTime"
                format="YYYY-MM-DD HH:mm:ss"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                show-time
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item>
              <div class="flex items-center">
                <a-button type="primary" class="mr-2" @click="onSearch">查询</a-button>
                <template v-if="spinning">
                  <a-alert message="回放视频加载中..." type="warning" />
                </template>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="jeecg-table-view flex justify-between p-3">
      <div class="tree-meun">
        <a-tree v-model="selectedKeys" :tree-data="treeData" showLine :load-data="onLoadData" @select="onSelect" :multiple="false">
          <template #title="vo">
            <div class="flex items-center">
              <span>{{ vo.name }}</span>
              <template v-if="vo['basicData']">
                <span class="status on-line"></span>
              </template>
            </div>
          </template>
        </a-tree>
      </div>
      <div class="timeline">
        <ul>
          <template v-for="(vo, idx) in timelineList" :key="idx">
            <li class="flex items-center justify-center" @click="playBackVideo(vo, idx)">
              <a-tag :color="activeIndex == idx ? 'orange' : 'blue'">
                <VideoCameraOutlined />
                {{ vo.start }} - {{ vo.end }}
              </a-tag>
            </li>
          </template>
        </ul>
      </div>
      <div class="video-player mb-5">
        <!-- <a-spin :spinning="spinning" tip="加载中..." :delay="500">
          <video :src="videoUrl" controls autoplay></video>
        </a-spin> -->
        <player ref="recordVideoPlayer" :videoUrl="videoUrl" :height="true" fluent autoplay live />
        <div class="time-line">
          <div class="flex items-center justify-center">
            <a-date-picker v-model:value="timeRange[0]" picker="time" format="HH:mm:ss" valueFormat="HH:mm:ss" @change="timePickerChange" />
            <a-divider type="vertical" />
            <a-date-picker v-model:value="timeRange[1]" picker="time" format="HH:mm:ss" valueFormat="HH:mm:ss" @change="timePickerChange" />
          </div>
          <div class="timeline-main">
            <a-slider
              v-model:value="playTime"
              range
              :min="sliderMIn"
              :max="sliderMax"
              :marks="marks"
              :tip-formatter="playTimeFormat"
              :disabled="timelineList.length == 0"
              @afterChange="changePlayTime"
            />
            <!-- <div class="slider-val-box">
              <template v-for="(item, idx) in timelineList" :key="idx">
                <div class="slider-val" :style="'width:' + getDataWidth(item) + '%; left:' + getDataLeft(item) + '%'"></div>
              </template>
            </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import {
  deviceQueryApi,
  deviceQueryTeeApi,
  deviceCameraPlayApi,
  cameraGbRecordQueryApi,
  cameraPlayBackStopApi,
  cameraPlayBackApi,
  deviceQueryBackApi,
  queryChannelsApi,
} from '@/api/camera/play';
import { wvpDevicesApi, wvpDeviceTreeApi, wvpPlaybackStartApi, wvpPlaybackQueryApi, wvpPlaybackStopApi } from '/@/api/wvp/index';
import { getAppEnvConfig } from '/@/utils/env';
import { useUserStore } from '/@/store/modules/user';
// import player from './components/easyPlayer.vue';
import player from './components/jessibuca.vue';
import { stationListApi } from '@/api/station/index';
import { CAMERA_CONFIG as cameraConfig } from '/@/utils/index.ts';
import { VideoCameraOutlined } from '@ant-design/icons-vue';
import moment from 'moment';

const userStore = useUserStore();

let { proxy } = getCurrentInstance();

let playTime = ref([]);

let chooseDate = moment().format('YYYY-MM-DD');

let startDateTime = moment().startOf('day').format('YYYY-MM-DD HH:mm:ss');

let endDeteTime = moment().endOf('day').format('YYYY-MM-DD HH:mm:ss');

let queryParam = ref({
  dateTime: [startDateTime, endDeteTime],
});

let spinning = ref(false);

let activeIndex = ref(-1);

let selectedKeys = ref([]);

let treeData = ref([]);

let streamInfo = null;

let videoUrl = ref('');

// 站点列表
let stationList = ref();

// 站点名称
let stationNames = ref([]);

// 站点名称
let stationName = '';

let cameraName = ref([]);

let timelineList = ref([]);

let streamId = '';

let deviceId = '';

let channelId = '';

let timeRange = ref([]);

let hasAudio = ref(false);

let ipagination = ref({
  current: 1,
  pageSize: 100000,
  pageSizeOptions: ['10', '20', '30'],
  showTotal: (total, range) => {
    return range[0] + '-' + range[1] + ' 共' + total + '条';
  },
  showQuickJumper: true,
  showSizeChanger: true,
  total: 0,
});

let sliderMIn = ref(0);
let sliderMax = ref(86400);
let marks = ref({
  0: '00:00',
  3600: '01:00',
  7200: '02:00',
  10800: '03:00',
  14400: '04:00',
  18000: '05:00',
  21600: '06:00',
  25200: '07:00',
  28800: '08:00',
  32400: '09:00',
  36000: '10:00',
  39600: '11:00',
  43200: '12:00',
  46800: '13:00',
  50400: '14:00',
  54000: '15:00',
  57600: '16:00',
  61200: '17:00',
  64800: '18:00',
  68400: '19:00',
  72000: '20:00',
  75600: '21:00',
  79200: '22:00',
  82800: '23:00',
  86400: '24:00',
});

/**
 * 初始化所有设备数据
 */
function onInitDeviceQuery() {
  let { current, pageSize } = ipagination.value;
  let data = {
    page: current,
    count: pageSize,
  };
  deviceQueryApi(data).then(({ list }) => {
    const userInfo = userStore.getUserInfo;
    let names = stationNames.value;
    if (userInfo.username !== 'admin') {
      treeData.value = list.filter((_) => {
        if (names.includes(_['name'])) {
          _['title'] = _['name'] == 'beijiao' ? '北滘水厂' : _['name'];
          _['key'] = _['deviceId'];
          return _;
        }
      });
    } else {
      if (list.length == 0) {
      } else {
        treeData.value = list.map((_) => {
          _['title'] = _['name'] == 'beijiao' ? '北滘水厂' : _['name'];
          _['key'] = _['deviceId'];
          return _;
        });
      }
    }
  });
}

/**
 * 选择时间抽
 */
function changePlayTime(val) {
  let startTime = moment(new Date(chooseDate + ' 00:00:00').getTime() + val[0] * 1000).format('YYYY-MM-DD HH:mm:ss');

  let endTime = moment(new Date(chooseDate + ' 00:00:00').getTime() + val[1] * 1000).format('YYYY-MM-DD HH:mm:ss');
  let info = timelineList.value[activeIndex.value];
  info['startTime'] = startTime;
  info['endTime'] = endTime;

  setTime(startTime, endTime);

  playBackVideo(info, activeIndex.value);
}

/**
 * 搜索视频时间段
 */
function onSearch() {
  let [startTime, endTime] = queryParam.value.dateTime;
  cameraGbRecordQueryApi({ deviceId, channelId }, { startTime, endTime }).then((res: any) => {
    let { recordList } = res;
    if (recordList.length !== 0) {
      let list = res.recordList;
      list.map((_) => {
        _['start'] = moment(_.startTime).format('HH:mm:ss');
        _['end'] = moment(_.endTime).format('HH:mm:ss');
        return _;
      });
      timelineList.value = list;
      // 默认播放第一个
      playBackVideo(list[0], 0);
    }
  });
}

function onLoadData(treeNode) {
  return new Promise((resolve) => {
    let deviceId = treeNode.deviceId;
    if (!treeNode.dataRef.ip) {
      resolve('');
      return;
    }
    wvpDeviceTreeApi(deviceId, { viewType: 2 }).then(({ list }) => {
      interface childType {
        key: string;
        title: string;
      }
      let children: childType[] = [];
      list.map((_) => {
        delete _['parent'];
        children.push({
          key: `${treeNode.eventKey}-${_['id']}`,
          title: _['name'],
          ..._,
          isLeaf: true,
        });
      });
      treeNode.dataRef.children = children;
      treeData.value = [...treeData.value];
      resolve(list);
    });
  });
}

/**
 * 选择摄像头播放视频流
 */
function onSelect(data, event) {
  selectedKeys.value = data.length ? [data[data.length - 1]] : [];
  playTime.value = [];
  if (event.selectedNodes[0]) {
    let { basicData } = event.selectedNodes[0];
    if (basicData) {
      stationName = event?.node?.parent?.node?.name;
      let [startTime, endTime] = queryParam.value.dateTime;
      channelId = basicData['channelId'];
      deviceId = basicData['deviceId'];
      wvpPlaybackQueryApi({ deviceId, channelId }, { startTime, endTime }).then((res) => {
        let list = res.recordList;
        list.map((_) => {
          _['start'] = moment(_.startTime).format('HH:mm:ss');
          _['end'] = moment(_.endTime).format('HH:mm:ss');
          return _;
        });
        timelineList.value = list;
        let dateTime = [
          moment(list[0]['startTime']).format('YYYY-MM-DD HH:mm:ss'),
          moment(list[list.length - 1]['endTime']).format('YYYY-MM-DD HH:mm:ss'),
        ];

        let start: any = (new Date(dateTime[0]).getTime() - new Date(chooseDate + ' 00:00:00').getTime()) / 1000;

        let end: any = (new Date(dateTime[1]).getTime() - new Date(chooseDate + ' 00:00:00').getTime()) / 1000;
        playTime.value = [start, end];

        // 默认播放第一个
        playBackVideo(list[0], 0);
      });
    }
  }
}

function setTime(startTime, endTime) {
  // startDateTime = startTime;
  // endDeteTime = endTime;
  let start = (new Date(startTime).getTime() - new Date(chooseDate + ' 00:00:00').getTime()) / 1000;
  let end = (new Date(endTime).getTime() - new Date(chooseDate + ' 00:00:00').getTime()) / 1000;

  // playTime.value = [start, end];
  timeRange.value = [moment(startTime).format('HH:mm:ss'), moment(endTime).format('HH:mm:ss')];
}

function timePickerChange() {
  let [a, b] = timeRange.value;
  let s = moment(`${chooseDate} ${a}`).format('YYYY-MM-DD HH:mm:ss');
  let e = moment(`${chooseDate} ${b}`).format('YYYY-MM-DD HH:mm:ss');
  let info = timelineList.value[activeIndex.value];
  info['startTime'] = s;
  info['endTime'] = e;
  setTime(s, e);
  playBackVideo(info, activeIndex.value);
}

function getTimeForFile(data) {
  let startTime = new Date(data.startTime);
  let endTime = new Date(data.endTime);
  return [startTime, endTime, endTime.getTime() - startTime.getTime()];
}

function getDataWidth(item) {
  let timeForFile: any = getTimeForFile(item);
  let result = timeForFile[2] / ((sliderMax.value - sliderMIn.value) * 1000);
  return result * 100;
}

function getDataLeft(item) {
  let timeForFile = getTimeForFile(item);
  let differenceTime = timeForFile[0].getTime() - new Date(chooseDate + ' 00:00:00').getTime();
  return parseFloat((differenceTime - sliderMIn.value * 1000) / ((sliderMax.value - sliderMIn.value) * 1000)) * 100;
}

function playTimeFormat(val) {
  let h = parseInt(val / 3600);
  let m = parseInt((val - h * 3600) / 60);
  let s = parseInt(val - h * 3600 - m * 60);

  let hStr = h;
  let mStr = m;
  let sStr = s;
  if (h < 10) {
    hStr = '0' + hStr;
  }
  if (m < 10) {
    mStr = '0' + mStr;
    s;
  }
  if (s < 10) {
    sStr = '0' + sStr;
  }
  return hStr + ':' + mStr + ':' + sStr;
}

/**
 * 开始回放视频播放
 */
function playBackVideo(dataValue, idx) {
  let { startTime, endTime } = dataValue;
  setTime(startTime, endTime);
  let query = {
    deviceId,
    channelId,
  };
  let data = {
    startTime,
    endTime,
    stationName,
  };
  activeIndex.value = idx;
  spinning.value = true;
  if (streamId !== '') {
    query['streamId'] = streamId;
    playBack(query, { stationName }).then((res) => {
      wvpPlaybackStartApi(query, data).then((res) => {
        spinning.value = false;
        streamInfo = res;
        streamId = streamInfo.stream;
        proxy.$refs['recordVideoPlayer'].onPlay(res.ws_flv);
      });
    });
  } else {
    wvpPlaybackStartApi(query, data).then((res) => {
      spinning.value = false;
      streamInfo = res;
      streamId = streamInfo.stream;
      // videoUrl.value = res.ws_flv;
      proxy.$refs['recordVideoPlayer'].onPlay(res.ws_flv);
    });
  }
}

function playBack(data, params) {
  return new Promise((resolve, reject) => {
    wvpPlaybackStopApi(data, params).then((res) => {
      resolve('');
    });
  });
}

/**
 * 初始化站点
 */
function initStation() {
  let stationCodes = userStore.getUserInfo['stationCodes'];
  let data = {};
  if (stationCodes) {
    data['stationCodes'] = stationCodes;
  }
  wvpDevicesApi(data).then((res) => {
    treeData.value = res.list.map((k) => {
      k['title'] = k['name'];
      k['key'] = k['deviceId'];
      return k;
    });
  });
  // stationListApi({}).then((res: any) => {
  //   let list = res.filter((k) => {
  //     if (stationCodes.split(',').includes(k['stationCode'])) {
  //       let code = cameraConfig[k['stationCode']].t2;
  //       stationNames.value.push(code == 'beijiao' ? '北滘' : code);
  //     }
  //   });
  //   stationList.value = list;
  //   // 初始化设备数据
  //   onInitDeviceQuery();
  // });
}

onMounted(() => {
  initStation();
});
</script>

<style lang="less" scoped>
.pump-room-container {
  margin: 12px;
  background: #fff;
  .tip {
    width: 100%;
    height: 44px;
    padding: 0 0 0 43.3px;
    background: url('@/assets/images/img-17.png') no-repeat;
    background-size: 100% 100%;
    line-height: 44px;
    span {
      font-size: 16px;
      color: #fff;
    }
  }
  .jeecg-search-layer {
    padding: 12px 15px 0;
    background: #fff;
    border-radius: 8px;
    .ant-form {
      max-width: auto;
      .ant-form-item {
        margin-bottom: 0;
      }
      :deep(.ant-col) {
        width: auto;
      }
    }
  }
  .jeecg-table-view {
    height: calc(100vh - 190px);
    .tree-meun {
      width: 20%;
      height: calc(100% - 24px);
      background: #fff;
      padding: 12px;
      overflow: hidden;
      overflow-y: scroll;
      .ant-tree {
        .status {
          display: block;
          width: 12px;
          height: 12px;
          margin: 0 0 0 6px;
          border-radius: 50%;
          &.on-line {
            background: #21da13;
          }
          &.off-line {
            background: red;
          }
        }
      }
    }
    .timeline {
      width: 185px;
      height: calc(100% - 24px);
      padding: 12px;
      background: #fff;
      overflow: hidden;
      overflow-y: scroll;
      ul {
        li {
          margin: 0 0 12px;
          cursor: pointer;
          .ant-tag {
            margin: 0;
          }
        }
      }
    }
    .video-player {
      height: calc(100% - 130px);
      margin: 0 0 0 12px;
      flex: 1;
      video {
        width: calc(100% - 12px);
        height: auto;
        background: #eee;
      }
      .time-line {
        margin: 12px 12px 0;
        .timeline-main {
          .slider-val-box {
            position: relative;
            top: -36px;
            width: 100%;
            height: 3.98px;
            .slider-val {
              position: absolute;
              height: 100%;
              background: #8cc8ff;
            }
          }
        }
      }
    }
  }
}
</style>